﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Data;
using Portal.Web.Model;
using Portal.Utility;
using Portal.Web.Utility;
using Portal.Exam.Model;
using Portal.Exam.Bussiness;
using Portal.Core;
using Spire.Xls;

namespace Portal.Exam.Render
{
    public class ImportExamRoomStudent
    {
        public static AjaxOut Draw(string SiteId)
        {
            AjaxOut OAjaxOut = new AjaxOut();

            string ExamRoomId = (string)WebEnvironments.Request(SiteId, "ExamRoomId");
            try
            {
                SiteParam OSiteParam = WebEnvironments.CreateSiteParam(SiteId);
                string IconRoot = WebConfig.GetButtonIconRoot(OSiteParam);

                ExamRoomCls OExamRoom = new ExamRoomBll().CreateModel(SiteId, ExamRoomId);
                if (OExamRoom == null) throw new Exception("Tham số không hợp lệ!");

                string RetHtml =
                    " <script language=javascript> \r\n" +
                    " StartLine=" + (ExamUltility.StartRowExcel - 1) + ";\r\n" +
                    " MaxLine=0;\r\n" +
                    "function fileSelected() {\r\n" +
                    "    var file = document.getElementById('fileToUpload').files[0];\r\n" +
                    "    if (file) {\r\n" +
                    "        var fileSize = 0;\r\n" +
                    "        if (file.size > 1024 * 1024)\r\n" +
                    "            fileSize = (Math.round(file.size * 100 / (1024 * 1024)) / 100).toString() + 'MB';\r\n" +
                    "        else\r\n" +
                    "            fileSize = (Math.round(file.size * 100 / 1024) / 100).toString() + 'KB';\r\n" +
                    "        document.getElementById('fileName').innerHTML = 'Tên tệp: ' + file.name;\r\n" +
                    "        document.getElementById('fileSize').innerHTML = 'Kích cỡ: ' + fileSize;\r\n" +
                    "        document.getElementById('fileType').innerHTML = 'Loại tệp: ' + file.type;\r\n" +
                    "    }\r\n" +
                    "}\r\n" +

                    "function uploadFile() {\r\n" +
                    "    if(confirm('Bạn đã chắc chắn nhập dữ liệu từ file chưa?')==false)return;\r\n" +
                    "    var fd = new FormData();\r\n" +
                    "    fd.append(\"fileToUpload\", document.getElementById('fileToUpload').files[0]);\r\n" +
                    "    var xhr = new XMLHttpRequest();\r\n" +
                    "    xhr.upload.addEventListener(\"progress\", uploadProgress, false);\r\n" +
                    "    xhr.addEventListener(\"load\", uploadComplete, false);\r\n" +
                    "    xhr.addEventListener(\"error\", uploadFailed, false);\r\n" +
                    "    xhr.addEventListener(\"abort\", uploadCanceled, false);\r\n" +
                    "    xhr.open(\"POST\", \"UploadHandler.ashx?SiteId=" + SiteId + "\");\r\n" +
                    "    xhr.send(fd);\r\n" +
                    "}\r\n" +

                    "function uploadProgress(evt) {\r\n" +
                    "    if (evt.lengthComputable) {\r\n" +
                    "    }\r\n" +
                    "    else {\r\n" +
                    "    }\r\n" +
                    "}\r\n" +

                    "function uploadComplete(evt) {\r\n" +
                    "    if(evt.target.responseText=='')\r\n" +
                    "    {\r\n" +
                    "       alert('Chưa chọn file để import!');\r\n" +
                    "       return;\r\n" +
                    "    }\r\n" +
                    "    /* This event is raised when the server send back a response */\r\n" +
                    "    document.getElementById('txtImportFile').value=evt.target.responseText;\r\n" +
                    "    //doan nay chay upload vao day...\r\n" +
                    "    ProcessImportFile()\r\n" +
                    "}\r\n" +

                    "function ProcessImportFile()\r\n" +
                    "{\r\n" +
                    "    SiteId='" + SiteId + "';\r\n" +
                    "    ImportFile=document.getElementById('txtImportFile').value;\r\n" +
                    "    if(ImportFile=='')\r\n" +
                    "    {\r\n" +
                    "       alert('Chưa có file để nhập liệu!');\r\n" +
                    "       return;\r\n" +
                    "    }\r\n" +
                    "    AjaxOut = Portal.Exam.Render.ImportExamRoomStudent.ServerSideReadMaxLine(SiteId, ImportFile).value;\r\n" +
                    "    MaxLine=AjaxOut.RetNumber;\r\n" +
                    "    if(MaxLine==0)\r\n" +
                    "    {\r\n" +
                    "       alert('Không có dữ liệu để import!');\r\n" +
                    "       return;\r\n" +
                    "    }\r\n" +
                    "    StartLine=" + (ExamUltility.StartRowExcel - 1) + ";\r\n" +
                    "    document.getElementById('divImportLog').innerHTML='';\r\n" +
                    "    document.getElementById('divImportLog').style.display='block';\r\n" +
                    "    setTimeout('ImportData()',30);\r\n" +
                    "    document.getElementById('divMaxline').innerHTML='Số sinh viên import:'+ (MaxLine-9);\r\n" +
                    "    document.getElementById('divMaxline').style.display='block';\r\n" +
                    "}\r\n" +

                    "function ImportData()\r\n" +
                    "{\r\n" +
                    "    if(StartLine==MaxLine)\r\n" +
                    "    {\r\n" +
                    "       StartLine=0;\r\n" +
                    "       MaxLine=0;\r\n" +
                    "       ProcessBarText = Portal.Exam.Render.ImportExamRoomStudent.ServerSideGetProcessBar(SiteId, MaxLine, MaxLine).value;\r\n" +
                    "       document.getElementById('divProcessing').innerHTML='';\r\n" +
                    "    }\r\n" +
                    "    else\r\n" +
                    "    {\r\n" +
                    "       ProcessBarText = Portal.Exam.Render.ImportExamRoomStudent.ServerSideGetProcessBar(SiteId, StartLine, MaxLine).value;\r\n" +
                    "       document.getElementById('divProcessing').innerHTML=ProcessBarText;\r\n" +
                    "       ImportFile=document.getElementById('txtImportFile').value;\r\n" +
                    "       ExamRoomId='" + ExamRoomId + "';\r\n" +
                    "       AjaxOut = Portal.Exam.Render.ImportExamRoomStudent.ServerSideProcessLine(SiteId, ExamRoomId, ImportFile, StartLine, MaxLine).value;\r\n" +
                    "       ImportLog=document.getElementById('divImportLog').innerHTML;\r\n" +
                    "       if(AjaxOut.Error)\r\n" +
                    "       {\r\n" +
                    "           document.getElementById('divImportLog').innerHTML=AjaxOut.InfoMessage+'<br>'+ImportLog;\r\n" +
                    "       }\r\n" +
                    "       StartLine=StartLine+1;\r\n" +
                    "       setTimeout('ImportData()',30);\r\n" +
                    "    }\r\n" +
                    "}\r\n" +



                    "function uploadFailed(evt) {\r\n" +
                    "    alert(\"Lỗi khi tải tệp dữ liệu lên máy chủ.\");\r\n" +
                    "}\r\n" +

                    "function uploadCanceled(evt) {\r\n" +
                    "    alert(\"Người dùng hủy bỏ tải lên máy chủ hoặc mất kết nối với máy chủ.\");\r\n" +
                    "}\r\n" +

                    " </script>\r\n" +
                    " <div class=DatabaseFunction>\r\n" +
                    "        <ul>\r\n" +
                    "            <li onclick=\"javascript:uploadFile();\"><img class=image src=\"" + IconRoot + "/Execute.png\"><div>Thực hiện</div></li>\r\n" +
                    "            <li onclick=\"javascript:window.open('ExamRoomStudent.aspx?ExamRoomId=" + ExamRoomId + "','_self');\"><img class=image src=\"" + IconRoot + "/back.png\"><div>Quay lại</div></li>\r\n" +
                    "        </ul>\r\n" +
                    "  </div>\r\n" +
                    "  <h3>Nhập dữ liệu sinh viên vào phòng thi - " + OExamRoom.RoomNo + " / " + OExamRoom.ExamSubject + "</h3>\r\n" +
                    "  <div class=CssImportForm>\r\n" +
                    "       <input type=hidden id=txtSMSServiceIds value=\"\">\r\n" +
                    "       <h3>Chọn tệp dữ liệu để import</h3>\r\n" +
                    "       <label for=\"fileToUpload\">Chọn tệp dữ liệu unicode</label>\r\n" +
                    "       <input type=\"file\" name=\"fileToUpload[]\" id=\"fileToUpload\" onchange=\"fileSelected();\" /><div style=\"margin-top:10px;\"></div>\r\n" +//<input type=button class=button onclick=\"uploadFile()\" value=\"Thực hiện nhập dữ liệu từ tệp\" /><input type=button class=button onclick=\"SaveLog()\" value=\"Ghi Log import\" />
                    "       <div id=divLinkSaveLog></div>\r\n" +
                    "       <div id=\"fileName\">\r\n" +
                    "       </div>\r\n" +
                    "       <div id=\"fileSize\">\r\n" +
                    "       </div>\r\n" +
                    "       <div id=\"fileType\">\r\n" +
                    "       </div>\r\n" +
                    "       <div id=divProcessing></div>\r\n" +
                    "       <div id=\"divImportLog\" style=\"padding:4px;border:solid 1px silver;height:200px;overflow:auto;display:none;\"></div>\r\n" +
                    "       <div id=\"divMaxline\" style=\"padding:4px;border:solid 1px silver;height:15px;overflow:auto;display:block;\"></div>\r\n" +
                    
                    "       <input type=hidden id=txtImportFile value=\"\">\r\n" +
                    "       <div class=CssTip style=\"color:maroon;font-size:12px;\"><i>(*) Chú ý: File phải đúng định dạng quy định theo <a href=\"ExcelTemplate/ExamStudentList.xls\">biểu mẫu</a></i></div>\r\n" +
                    "  </div>\r\n";

                OAjaxOut.HtmlContent = RetHtml;
            }
            catch (Exception ex)
            {
                OAjaxOut.Error = true;
                OAjaxOut.HtmlContent = ex.Message.ToString();
                OAjaxOut.InfoMessage = ex.Message.ToString();
            }
            return OAjaxOut;
        }

        [AjaxPro.AjaxMethod]
        public static AjaxOut ServerSideReadMaxLine(string SiteId, string ImportFile)
        {
            AjaxOut OAjaxOut = new AjaxOut();
            try
            {
                Workbook workbook = new Workbook();
                workbook.LoadFromFile(ImportFile);
                Worksheet worksheet = workbook.Worksheets[0];
                int StartLineIndex = ExamUltility.StartRowExcel;
                string Data = worksheet.Rows[StartLineIndex].Cells[0].Text;
                int MaxRow = 0;
                while (!string.IsNullOrEmpty(Data))
                {
                    MaxRow++;
                    StartLineIndex++;
                    Data = worksheet.Rows[StartLineIndex].Cells[0].Text;
                }

                MaxRow += ExamUltility.StartRowExcel - 1;
                //string[] Data = System.IO.File.ReadAllLines(ImportFile);
                OAjaxOut.RetNumber = MaxRow;
                workbook.Dispose();
            }
            catch (Exception ex)
            {
                OAjaxOut.Error = true;
                OAjaxOut.InfoMessage = ex.Message.ToString();
            }

            return OAjaxOut;
        }

        [AjaxPro.AjaxMethod]
        public static string ServerSideGetProcessBar(string SiteId, int ProcessLine, int MaxLine)
        {
            MaxLine = MaxLine - 9;
            ProcessLine = ProcessLine - 9;
            int MaxW = 700;
            decimal W = 0;
            decimal Percent = 0;
            if (MaxLine > 0)
            {
                W = (decimal)MaxW * (decimal)ProcessLine / (decimal)MaxLine;
                Percent = ((decimal)ProcessLine / (decimal)MaxLine) * 100;
            }
            if (Percent < 1) Percent = 1;
            if (Percent > 100) Percent = 100;
            string HtmlProgressBar = "<div style=\"width:" + MaxW + "px;padding:10px; background-color:silver;border:solid 1px black;height:55px;margin-top:10px;margin-bottom:10px;\">\r\n" +
                                     "   <div style=\"padding:4px;\">Xử lý dòng " + (ProcessLine + 1) + "/" + MaxLine + "</div>\r\n" +
                                     "   <div style='border:solid 1px black;padding:4px;background-color:blue;color:white;width:" + W.ToString("###0") + "px'>" + Percent.ToString("#,##0") + "% </div>\r\n" +
                                     "</div>\r\n";

            return HtmlProgressBar;
        }


        [AjaxPro.AjaxMethod]
        public static AjaxOut ServerSideProcessLine(
            string SiteId,
            string ExamRoomId,
            string ImportFile,
            int ProcessLine,
            int MaxLine)
        {
            AjaxOut OAjaxOut = new AjaxOut();
            OAjaxOut.InfoMessage = "";
            try
            {
                WebSessionUtility.CheckSessionTimeOut();
                int RecordIndex = ProcessLine;
                if (RecordIndex == MaxLine)
                {
                    return OAjaxOut;
                }

                Workbook workbook = new Workbook();
                workbook.LoadFromFile(ImportFile);
                Worksheet worksheet = workbook.Worksheets[0];

                int ReadLine = ProcessLine + 1;

                string UniCode = WebSessionUtility.GetCurrentLoginUser().AssetCode;


                string StudentCode = worksheet.Rows[ReadLine].Cells[2].Text;
                string StudentName = worksheet.Rows[ReadLine].Cells[3].Text;
                //string Sex = worksheet.Rows[ReadLine].Cells[2].Text;

                string Sex = "nam";
                int iSex = 0;
                if (Sex.ToLower().Equals("nam"))
                {
                    iSex = 1;
                }
                //string sDob = worksheet.Rows[ReadLine].Cells[3].Text;
                DateTime Dob = new System.DateTime();
                try
                {
                    //Dob = FunctionUtilities.VNDateToDate(sDob);
                }
                catch { }
                //string Course = worksheet.Rows[ReadLine].Cells[4].Text;
                //string Course = worksheet.Rows[5].Cells[3].Text != null ? worksheet.Rows[5].Cells[3].Text : "";
                string Course = "";
                string Class = worksheet.Rows[ReadLine].Cells[5].Text != null ? worksheet.Rows[ReadLine].Cells[5].Text : "";
                string TrainingLevel = worksheet.Rows[ReadLine].Cells[6].Text != null ? worksheet.Rows[ReadLine].Cells[6].Text : "";

                new ExamRoomStudentBll().CreateExamRoomStudent(null, SiteId, ExamRoomId, StudentCode, StudentName, iSex, Dob, Course, Class, TrainingLevel, UniCode);
                workbook.Dispose();
                #region old
                //OAjaxOut.InfoMessage = "";// "Dòng: " + (ProcessLine + 1) + " xử lý sinh viên mã [" + StudentCode + "] thành công!";

                //string[] Data = System.IO.File.ReadAllLines(ImportFile);
                //string ItemData = Data[ProcessLine];
                //ItemData = ItemData.Trim();
                //if (string.IsNullOrEmpty(ItemData))
                //{
                //    return OAjaxOut;
                //}
                //string UniCode = WebSessionUtility.GetCurrentLoginUser().AssetCode;
                //string[] Items = ItemData.Split(new char[] { '\t' }, StringSplitOptions.RemoveEmptyEntries);
                //if (Items.Length == 7)
                //{
                //    string StudentCode=Items[0];
                //    string StudentName=Items[1];
                //    string Sex=Items[2];
                //    int iSex=0;
                //    if(Sex.ToLower().Equals("nam"))
                //    {
                //        iSex=1;
                //    }
                //    string sDob = Items[3];
                //    DateTime Dob = new System.DateTime();
                //    try
                //    {
                //        Dob = FunctionUtilities.VNDateToDate(sDob);
                //    }
                //    catch { }
                //    string Course=Items[4];
                //    string Class=Items[5];
                //    string TrainingLevel=Items[6];
                //    new ExamRoomStudentBll().CreateExamRoomStudent(null, SiteId, ExamRoomId, StudentCode, StudentName, iSex, Dob, Course, Class, TrainingLevel, UniCode);
                //    OAjaxOut.InfoMessage = "";// "Dòng: " + (ProcessLine + 1) + " xử lý sinh viên mã [" + StudentCode + "] thành công!";
                //    //OAjaxOut.InfoMessage = new SMSQueueBll().ProcessQueueImportItem(SiteId,SMSQueueId, StudentCode, SendSMSContent);
                //}
                //else
                //{
                //    OAjaxOut.Error = true;
                //    OAjaxOut.InfoMessage = "Dữ liệu không hợp lệ!";
                //}
                #endregion
            }
            catch (Exception ex)
            {
                OAjaxOut.Error = true;
                OAjaxOut.InfoMessage = "Lỗi xử lý dòng " + (ProcessLine + 1) + " => " + ex.Message.ToString();
            }
            return OAjaxOut;
        }
    }
}
